<template>
  <div class="level-list">
    <el-container>
      <el-main>
        <div class="list-content">
          <!-- 页面标题和操作栏 -->
          <el-row :gutter="24" class="header-section">
            <el-col :span="24">
              <div class="page-header">
                <h1 class="page-title">找茬游戏关卡</h1>
                <div class="header-actions">
                  <el-button type="primary" @click="$router.push('/findproblem/add')" :icon="Plus">
                    创建关卡
                  </el-button>
                </div>
              </div>
            </el-col>
          </el-row>

          <!-- 搜索和筛选栏 -->
          <el-row :gutter="24" class="filter-section">
            <el-col :span="24">
              <el-card shadow="never" class="filter-card">
                <el-form :model="searchForm" :inline="true" class="search-form">
                  <el-form-item label="关卡标题">
                    <el-input
                        v-model="searchForm.title"
                        placeholder="请输入关卡标题"
                        clearable
                        style="width: 200px"
                        @input="handleSearch"
                    />
                  </el-form-item>
                  <el-form-item label="难度等级">
                    <el-select
                        v-model="searchForm.difficulty"
                        placeholder="请选择难度"
                        clearable
                        style="width: 120px"
                        @change="handleSearch"
                    >
                      <el-option label="简单" :value="1" />
                      <el-option label="中等" :value="2" />
                      <el-option label="困难" :value="3" />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleSearch" :icon="Search">
                      搜索
                    </el-button>
                    <el-button @click="resetSearch" :icon="Refresh">
                      重置
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>
          </el-row>

          <!-- 关卡列表 -->
          <el-row :gutter="24" class="content-section">
            <el-col :span="24">
              <el-card shadow="hover" class="list-card">
                <template #header>
                  <div class="card-header">
                    <span>关卡列表</span>
                    <el-tag type="info" size="small">共 {{ filteredLevels.length }} 个关卡</el-tag>
                  </div>
                </template>

                <div v-loading="loading" class="level-grid">
                  <div
                      v-for="level in paginatedLevels"
                      :key="level.id"
                      class="level-item"
                      @click="playLevel(level)"
                  >
                    <el-card shadow="hover" class="level-card">
                      <div class="level-image">
                        <img
                            :src="`http://127.0.0.1:8080${level.imageUrl}`"
                            :alt="level.title"
                            @error="handleImageError"
                        />
                        <div class="level-overlay">
                          <el-button type="primary" circle :icon="VideoPlay" size="large" />
                        </div>
                      </div>
                      <div class="level-info">
                        <h3 class="level-title">{{ level.title }}</h3>
                        <div class="level-meta">
                          <div class="meta-item">
                            <el-tag
                                :type="getDifficultyType(level.difficulty)"
                                size="small"
                            >
                              {{ getDifficultyText(level.difficulty) }}
                            </el-tag>
                          </div>
                          <div class="meta-item">
                            <el-icon><Clock /></el-icon>
                            <span>{{ level.timeLimit }}秒</span>
                          </div>
                          <div class="meta-item">
                            <el-icon><Location /></el-icon>
                            <span>{{ level.totalSpots }}个错误点</span>
                          </div>
                        </div>
                        <div class="level-actions">
                          <el-button type="primary" size="small" @click.stop="playLevel(level)">
                            开始游戏
                          </el-button>
                          <el-button type="info" size="small" @click.stop="editLevel(level)">
                            编辑
                          </el-button>
                          <el-button type="danger" size="small" @click.stop="deleteLevel(level)">
                            删除
                          </el-button>
                        </div>
                      </div>
                    </el-card>
                  </div>
                </div>

                <!-- 空状态 -->
                <el-empty v-if="!loading && filteredLevels.length === 0" description="暂无关卡数据">
                  <el-button type="primary" @click="$router.push('/findproblem/add')">
                    创建第一个关卡
                  </el-button>
                </el-empty>

                <!-- 分页 -->
                <div v-if="filteredLevels.length > 0" class="pagination-wrapper">
                  <el-pagination
                      v-model:current-page="currentPage"
                      v-model:page-size="pageSize"
                      :page-sizes="[8, 16, 24, 32]"
                      :total="filteredLevels.length"
                      layout="total, sizes, prev, pager, next, jumper"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                  />
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  VideoPlay,
  Clock,
  Location,
  Edit,
  Delete
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const levels = ref([])
const currentPage = ref(1)
const pageSize = ref(8)

// 搜索表单
const searchForm = reactive({
  title: '',
  difficulty: null
})

// 获取关卡列表
const fetchLevels = async () => {
  loading.value = true
  try {
    const response = await fetch('/dev-api/api/game/levels')
    const result = await response.json()
    
    if (result.code === 200) {
      levels.value = result.data || []
    } else {
      ElMessage.error('获取关卡列表失败：' + (result.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取关卡列表错误:', error)
    ElMessage.error('获取关卡列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 筛选后的关卡列表
const filteredLevels = computed(() => {
  return levels.value.filter(level => {
    const titleMatch = !searchForm.title || 
      level.title.toLowerCase().includes(searchForm.title.toLowerCase())
    const difficultyMatch = !searchForm.difficulty || 
      level.difficulty === searchForm.difficulty
    
    return titleMatch && difficultyMatch
  })
})

// 分页后的关卡列表
const paginatedLevels = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredLevels.value.slice(start, end)
})

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchForm.title = ''
  searchForm.difficulty = null
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 获取难度类型
const getDifficultyType = (difficulty) => {
  const types = { 1: 'success', 2: 'warning', 3: 'danger' }
  return types[difficulty] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty) => {
  const texts = { 1: '简单', 2: '中等', 3: '困难' }
  return texts[difficulty] || '未知'
}

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.src = ''
}

// 开始游戏
const playLevel = (level) => {
  router.push(`/findproblem/play/${level.id}`)
}

// 编辑关卡
const editLevel = (level) => {
  router.push(`/findproblem/edit/${level.id}`)
}

// 删除关卡
const deleteLevel = async (level) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除关卡「${level.title}」吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用删除API
    // const response = await fetch(`/api/admin/level/${level.id}`, { method: 'DELETE' })
    // const result = await response.json()
    
    // 模拟删除成功
    levels.value = levels.value.filter(l => l.id !== level.id)
    ElMessage.success('关卡删除成功!')
  } catch {
    // 用户取消删除
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLevels()
})
</script>

<style scoped>
.level-list {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 20px;
}

.list-content {
  max-width: 1400px;
  margin: 0 auto;
}

.header-section {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  color: #303133;
  font-size: 32px;
  font-weight: bold;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-card {
  border-radius: 12px;
}

.search-form {
  margin: 0;
}

.content-section {
  margin-bottom: 20px;
}

.list-card {
  border-radius: 12px;
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.level-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.level-item {
  cursor: pointer;
  transition: transform 0.3s ease;
}

.level-item:hover {
  transform: translateY(-4px);
}

.level-card {
  border-radius: 12px;
  overflow: hidden;
  height: 100%;
  transition: all 0.3s ease;
}

.level-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.level-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  background: #f5f7fa;
}

.level-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.level-item:hover .level-image img {
  transform: scale(1.05);
}

.level-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.level-item:hover .level-overlay {
  opacity: 1;
}

.level-info {
  padding: 16px;
}

.level-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.level-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #606266;
}

.meta-item .el-icon {
  font-size: 16px;
}

.level-actions {
  display: flex;
  gap: 8px;
  justify-content: space-between;
}

.level-actions .el-button {
  flex: 1;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .level-list {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .level-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .level-actions {
    flex-direction: column;
  }
  
  .level-actions .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .level-image {
    height: 150px;
  }
  
  .level-info {
    padding: 12px;
  }
  
  .level-title {
    font-size: 16px;
  }
}
</style>